package sort;

import java.util.Random;
import java.util.function.Function;

public class Util {

    public static int[] getRandomArray() {
        Random random = new Random();

        int len = random.nextInt(20) + 5;
        int[] result = new int[len];

        for (int i = 0; i < len; i++) {
            result[i] = random.nextInt(88);
        }

        return result;
    }

    public static void swap(int[] array, int index1, int index2) {
        int temp = array[index1];
        array[index1] = array[index2];
        array[index2] = temp;
    }

    public static boolean isSorted(int[] array) {
        for (int i = 0; i < array.length-1; i++) {
            int leftValue = array[i];
            int rightValue = array[i+1];
            if (leftValue > rightValue) {
                return false;
            }
        }

        return true;
    }

    public static void printArrayFormat(int[] array) {
        int len = array.length;
        System.out.print("[");
        for (int i = 0; i < len; i++) {
            if (i != len-1) {
                System.out.print(array[i] + ",");
            } else {
                System.out.print(array[i]);
            }
        }
        System.out.println("]");
    }

    /*
        测试排序函数是否正确的封装类
        Function<传入参数类型， 返回参数类型>
     */
    public static void testFunction(Function<int[], int[]> function) {
        // 生成数组并打印
        int[] array = Util.getRandomArray();
        Util.printArrayFormat(array);

        // 使用函数
        function.apply(array);

        // 打印排序后的函数
        Util.printArrayFormat(array);

        // 判断是否排对了
        System.out.println(isSorted(array) ? "排对了" : "排错了");
    }

    /*
        测试10000个示例
     */
    public static void testFunction10000(Function<int[], int[]> function) {
        boolean isSorted = false;

        for (int i = 0; i < 10000; i++) {
            // 生成数组并打印
            int[] array = Util.getRandomArray();

            // 使用函数
            function.apply(array);

            // 判断是否排对了
            isSorted = isSorted(array);
            if (!isSorted)  break;
        }

        System.out.println(isSorted ? "对了" : "错了");
    }
}
